// Copyright 2009 Google Inc. All Rights Reserved.

/**
 * @fileoverview Code for handling functionality specific to canvas view.
 */

/**
 * Maximum item to be shown on a page.
 * @const
 */
var MAX_ITEM = 15;

/**
 * Index of selected page.
 * @type {number}
 */
var selectedPage = 0;

/**
 * Total number of pages for selected category.
 * @type {number}
 */
var totalPages;

/**
 * Shorten the title to be fit in the fix.
 * @param {string} text content string.
 * @return {string} modified text.
 */
function shortenTitle(text) {
  if (text.length > 40) {
    text = text.substr(0, 40);
    if (text.charAt(text.length - 1) == ' ') {
      text = text.substr(0, text.length - 1);
    }
    text = text + '...';
  }
  return text;
}

/**
 * Shows the content.
 * @param {number} num Page index.
 */
function showContent(num) {
  if (num < 1 || num > totalPages) {
    return;
  }
  if (num > 1) {
    _gel('foodzie-page-prev').style.display = '';
  } else {
    _gel('foodzie-page-prev').style.display = 'none';
  }
  if (num < totalPages) {
    _gel('foodzie-page-next').style.display = '';
  } else {
    _gel('foodzie-page-next').style.display = 'none';
  }

  // Unselect the previous category and highlight selected one.
  var element = _gel('foodzie-page' + selectedPage);
  if (element) {
    element.className = 'foodzie-inactive';
  }
  element = _gel('foodzie-page' + num);
  if (element) {
    element.className = 'foodzie-active';
  }
  selectedPage = num;
  var html = ['<table cellspacing="0" cellpadding="5" width="100%" ' +
      'style="font-size:13px;"><tr>'];
  var startIndex = MAX_ITEM * (num - 1);
  var maxLen = Math.min(MAX_ITEM + startIndex, content.length);
  for (var i = startIndex + 1; i <= maxLen; i++) {
    var index = i - 1;
    var title = content[index].title;
    var subTitle = shortenTitle(title);
    var cellHtml = _gel('foodzie-item-tpl').value
        .replace(/%INDEX%/, index)
        .replace(/%LINK%/g, content[index].link)
        .replace(/%URL%/, content[index].img)
        .replace(/%TITLE%/g, title)
        .replace(/%SUBTITLE%/, subTitle)
        .replace(/%PRICE%/, content[index].price);
    html.push(cellHtml);
    if (!(i % 5)) {
      html.push('</tr><tr>');
    }
  }
  html.push('</tr></table>');
  var container = _gel('foodzie-content');
  container.style.display = 'block';
  container.innerHTML = html.join('');
  _IG_AdjustIFrameHeight();
}

/**
 * Creates body for the gadget.
 */
function createBody() {
  if (!content.length) {
    showMessage(prefs.getMsg('no_item_found'));
    if (_gel('foodzie-page-prev'))
      _gel('foodzie-page-prev').style.display = 'none';
    if (_gel('foodzie-page-next'))
      _gel('foodzie-page-next').style.display = 'none';
    return;
  }

  totalPages = Math.ceil(content.length / MAX_ITEM);

  var html = ['<div><span id="foodzie-page-prev" class="foodzie-previous" ',
      'onclick="showContent(selectedPage - 1);">', prefs.getMsg('prev'),
      '</span>'];

  if (totalPages > 1) {
    for (var i = 1; i <= totalPages; i++) {
      html.push('<span id="foodzie-page', i, '" class="foodzie-inactive" ',
          'onclick="showContent(', i, ');">', i, '</span>');
    }
  }
  html.push('<span id="foodzie-page-next" class="foodzie-next" ',
      'onclick="showContent(selectedPage + 1);">',
    prefs.getMsg('next'), '</span></div>');
  _gel('foodzie-pager').innerHTML = html.join('');

  showContent(1);
}

/**
 * Executes when click on any category.
 * @param {number} index Index of selected category.
 */
function changeCategory(index) {
  var selectedCategoryIndex = prefs.getInt('category');
  if (selectedCategoryIndex == index) {
    return;
  }
  var element = _gel('foodzie-category' + selectedCategoryIndex);
  element.style.backgroundColor = '#fff';
  element.style.cursor = 'pointer';
  prefs.set('category', index);
  init();
}

/**
 * Initializes global variables and user prefs and proceed further execution.
 */
function init() {
  var index = prefs.getInt('category');
  var element = _gel('foodzie-category' + index);
  if (element) {
    element.style.backgroundColor = '#d6e694';
    element.style.cursor = 'auto';
  }
  if (index != -1 && categoryObj[index]) {
    var url = FEED_URL + '';
    url = url.replace('CID', categoryObj[index].id + '');
    url = url.replace('LIMIT', '40');
    // dimensions of foodzie-item-image-container in foodzie-item-tpl
    fetchContent(url, 140, 140);
  }
}
// Entry point.
_IG_RegisterOnloadHandler(init);
